package com.example.coursedesign.ui.home;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.coursedesign.R;
import com.example.coursedesign.ui.home.dao.UserDataDao;
import com.example.coursedesign.ui.home.entity.UserData;

import java.io.IOException;
import java.io.InputStream;

public class HealthDataActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_PERMISSIONS = 1001;
    private static final String[] REQUIRED_PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE};

    private EditText heightInput, weightInput, heartRateInput, bloodPressureInput, bloodSugarInput;
    private TextView bmiResultText;
    private Button bmiCalculateButton, reportButton, saveButton, cancelButton;
    private UserDataDao userDataDao;
    private Uri selectedReportUri = null; // 用于存储所选文件的 URI
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.healthdata);

        // 初始化 UserDataDao
        userDataDao = new UserDataDao();

        heightInput = findViewById(R.id.height_input);
        weightInput = findViewById(R.id.weight_input);
        bmiResultText = findViewById(R.id.bmi_result_text);
        heartRateInput = findViewById(R.id.heart_rate);
        bloodPressureInput = findViewById(R.id.blood_pressure);
        bloodSugarInput = findViewById(R.id.blood_sugar);
        bmiCalculateButton = findViewById(R.id.bmi_calculate_button);
        reportButton = findViewById(R.id.report_button);
        saveButton = findViewById(R.id.save_button);
        cancelButton = findViewById(R.id.cancel_button);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        // 请求必要的权限
        if (!checkPermissions()) {
            requestPermissions();
        }

        bmiCalculateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculateBMI();
            }
        });

        reportButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadReport();
            }
        });

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveUserData();
            }
        });

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 返回上一个 Activity
            }
        });
    }

    private boolean checkPermissions() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void requestPermissions() {
        ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, continue with the operation
            } else {
                // Permission denied, show a message to the user
                Toast.makeText(this, "请授予文件读取权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void calculateBMI() {
        try {
            double height = Double.parseDouble(heightInput.getText().toString()) / 100; // Convert to meters
            double weight = Double.parseDouble(weightInput.getText().toString());
            double bmi = weight / (height * height);
            bmiResultText.setText("BMI: " + String.format("%.2f", bmi));
            bmiResultText.setVisibility(View.VISIBLE); // Make the result visible
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
        }
    }

    private void uploadReport() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*"); // Allow all file types
        intent.addCategory(Intent.CATEGORY_OPENABLE); // Ensure the file is openable

        // Optional: Add a title for the file picker
        String title = "请选择体检报告文件";
        Intent chooser = Intent.createChooser(intent, title);

        // Start the file picker activity
        startActivityForResult(chooser, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            selectedReportUri = data.getData();

            // Optional: Check file size
            try {
                ContentResolver contentResolver = getContentResolver();
                InputStream inputStream = contentResolver.openInputStream(selectedReportUri);
                if (inputStream != null) {
                    long fileSize = inputStream.available();
                    inputStream.close();

                    if (fileSize > MAX_FILE_SIZE) {
                        Toast.makeText(this, "文件过大，请选择小于5MB的文件", Toast.LENGTH_SHORT).show();
                        selectedReportUri = null; // Clear the URI if the file is too large
                        return;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "无法读取文件", Toast.LENGTH_SHORT).show();
                selectedReportUri = null;
                return;
            }

            // Optional: Show a toast to confirm the file selection
            Toast.makeText(this, "文件已选择", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveUserData() {
        try {
            // 获取账户名（假设从其他地方获取）
            String account = getAccountFromSomewhere(); // 你需要实现这个方法来获取账户名

            // 检查所有必填项是否已填写
            if (heightInput.getText().toString().isEmpty() || weightInput.getText().toString().isEmpty() ||
                    bloodPressureInput.getText().toString().isEmpty() || bloodSugarInput.getText().toString().isEmpty() ||
                    heartRateInput.getText().toString().isEmpty()) {
                Toast.makeText(this, "请填写所有必填项", Toast.LENGTH_SHORT).show();
                return;
            }
            // 解析用户输入
            double height = Double.parseDouble(heightInput.getText().toString());
            double weight = Double.parseDouble(weightInput.getText().toString());
            String bloodPressure = bloodPressureInput.getText().toString();
            double bloodSugar = Double.parseDouble(bloodSugarInput.getText().toString());
            int heartRate = Integer.parseInt(heartRateInput.getText().toString());
            // 创建 UserData 对象
            UserData userData = new UserData();
            userData.setAccount(account);
            userData.setHeight(height);
            userData.setWeight(weight);
            userData.setBloodPressure(bloodPressure);
            userData.setBloodSugar(bloodSugar);
            userData.setHeartRate(heartRate);
            userData.setPhysicalExamReport(selectedReportUri != null ? selectedReportUri.toString() : "");
            // 异步保存数据
            new SaveUserDataAsyncTask().execute(userData);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
        }
    }

    private String getAccountFromSomewhere() {
        // 实现获取账户名的逻辑，例如从 SharedPreferences 或者登录状态中获取
        return "user123"; // 这里只是一个示例
    }

    private class SaveUserDataAsyncTask extends AsyncTask<UserData, Void, Long> {

        @Override
        protected Long doInBackground(UserData... userDatas) {
            if (userDatas.length == 0) return -1L;
            return userDataDao.saveUserData(userDatas[0]);
        }

        @Override
        protected void onPostExecute(Long newRowId) {
            if (newRowId != -1) {
                Toast.makeText(HealthDataActivity.this, "数据保存成功", Toast.LENGTH_SHORT).show();
                finish(); // 结束当前 Activity 并返回上一个界面
            } else {
                Toast.makeText(HealthDataActivity.this, "数据保存失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed(); // 返回上一个 Activity
        return true;
    }
}